<?php

namespace App\Http\Controllers\Api;

use App\Model\Cart;
use App\Model\Goods;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class CartController extends Controller
{

    /**
     * @param Request $request
     * 购物车列表
     */
    public function index(Request $request){
        $cart = new Cart();
        $uid = $request->input("user_id");
        $cartInfo = $cart->select('cart.*','goods.name','goods.price','goods.thumb_img')->where('user_id',$uid)->leftJoin('goods','goods.id','=','goods_id')->orderBy('cart.created_at','desc')->get();
        if(count($cartInfo)>0){
            $this->success($cartInfo);
        }else{
            $this->error('购物车是空的');
        }
    }

    /**
     * @param Request $request
     * 添加到购物车接口
     */
    public function add(Request $request){
        $goods = new Goods();
        $cart = new Cart();
        $uid = $request->input("user_id");
        $gid = $request->input("goods_id");
        $num = $request->input("num");
        $goodsInfo = $goods->where('status','1')->find($gid);
        if(empty($uid) || empty($gid) || empty($num)){
            $this->error('参数错误');
        }
        if($goodsInfo['num'] < $num){
            $this->error('很抱歉，库存不足');
        }
        $cartInfo = $cart->where('user_id','=',$uid)->where('goods_id','=',$gid)->first();
        if(count($cartInfo)>0){
            $countNum = $num + $cartInfo['num'];
            if($countNum > $goodsInfo['num']){
                $this->error('库存不足');
            }else{
                $res = $cart->where('id',$cartInfo['id'])->update(array('num'=>$countNum));
            }
        }else{
            $cart->user_id = $uid;
            $cart->goods_id = $gid;
            $cart->num = $num;
            $cart->price = $goodsInfo['price'];
            $res = $cart->save();
        }
        if($res){
            $this->success('添加购物车成功！');
        }else{
            $this->error('添加失败'.__LINE__);
        }
    }

    /**
     * @param Request $request
     * 修改购物车某商品数量
     */
    public function reduce(Request $request){
        $cartId = $request->input("cartId");
        $num = $request->input("num");
        $cart = new Cart();
        if(empty($cartId) || empty($num)){
            $this->error('参数错误');
        }
        $res = $cart->where('id',$cartId)->update(array('num'=>$num));
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    
    //删除购物车商品
    public function delete(Request $request){
        $cartId = $request->input("cartId");
        if(empty($cartId)){
            $this->error('参数错误');
        }
        $cart = new Cart();
        $res = $cart->where('id',$cartId)->delete();
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
}
